package com.ly.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录验证失败处理器
 * @author ：LY
 * @date ：Created in 2020/11/9 19:36
 * @modified By：
 */
public class LoginAuthFailHandler extends SimpleUrlAuthenticationFailureHandler {

    private final LoginUrlEntryPoint urlEntryPoint ;

    public LoginAuthFailHandler(LoginUrlEntryPoint urlEntryPoint) {
        this.urlEntryPoint = urlEntryPoint;
    }



    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String targetUrl = this.urlEntryPoint.determineUrlToUseForThisRequest(request, response, exception);

//        System.out.println("username == "+urlEntryPoint.getUserName());
//        System.out.println("targetUrl===="+targetUrl);
//        String reg = " (?<=/)[\\D]{0,5}(?=/)";
//        if (urlEntryPoint.getUserName()!=null){
//            String reg = "(?<=\\/)(.*?)(?=\\/)";
//            System.out.println("最终"+targetUrl.replaceAll(reg,urlEntryPoint.getUserName()));
//            targetUrl = targetUrl.replaceAll(reg,urlEntryPoint.getUserName());
//            urlEntryPoint.setUserName(null);
//        }


        targetUrl += "?" + exception.getMessage();

        super.setDefaultFailureUrl(targetUrl);
        super.onAuthenticationFailure(request,response,exception);
    }
}
